﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using Deeper.Common;
using System.Management;
using Microsoft.Win32;
using System.Security.Permissions;
using System.Security;
using System.Web.Routing;
using System.Xml;
using System.Linq;


namespace Deeper.Common.Web
{
	public static class WebHelper
	{
		/// <summary>
		/// 当前页面
		/// </summary>
		internal static Page CurrentPage
		{
			get { return (Page)HttpContext.Current.Handler; }
		}

		/// <summary>
		/// 以指定的ContentType输出指定文件文件
		/// </summary>
		/// <param name="filepath">文件路径</param>
		/// <param name="filename">输出的文件名</param>
		/// <param name="filetype">将文件输出时设置的ContentType</param>
		public static void ResponseFile(string filepath, string filename, string filetype)
		{
			Stream iStream = null;

			// 缓冲区为10k
			byte[] buffer = new Byte[10000];

			// 文件长度
			int length;

			// 需要读的数据长度
			long dataToRead;

			try
			{
				// 打开文件
				iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);


				// 需要读的数据长度
				dataToRead = iStream.Length;

				HttpContext.Current.Response.ContentType = filetype;
				HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="
					+ HttpUtility.UrlEncode(filename.Trim()).Replace("+", " "));

				while (dataToRead > 0)
				{
					// 检查客户端是否还处于连接状态
					if (HttpContext.Current.Response.IsClientConnected)
					{
						length = iStream.Read(buffer, 0, 10000);
						HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
						HttpContext.Current.Response.Flush();
						buffer = new Byte[10000];
						dataToRead = dataToRead - length;
					}
					else
					{
						// 如果不再连接则跳出死循环
						dataToRead = -1;
					}
				}
			}
			catch (Exception ex)
			{
				HttpContext.Current.Response.Write("Error : " + ex.Message);
			}
			finally
			{
				if (iStream != null)
				{
					// 关闭文件
					iStream.Close();
				}
			}
			HttpContext.Current.Response.End();
		}

		/// <summary>
		/// 路由注册
		/// </summary>
		/// <param name="routes"></param>
		/// <param name="path"></param>
		/// <param name="app"></param>
		public static void RegisterRouters(RouteCollection routes, string path, HttpApplication app)
		{
			//MapPageRoute参数定义：(from Msdn)
			//routeName
			//类型：System.String
			//路由的名称。
			//routeUrl
			//类型：System.String
			//路由的 URL 模式。
			//physicalFile
			//类型：System.String
			//路由的物理 URL。
			//checkPhysicalUrlAccess
			//类型：System.Boolean
			//一个值，该值指示 ASP.NET 是否应验证用户是否有权访问物理 URL（始终会检查路由 URL）。 此参数设置 PageRouteHandler.CheckPhysicalUrlAccess 属性。 
			//defaults
			//类型：System.Web.Routing.RouteValueDictionary
			//路由参数的默认值。
			//constraints
			//类型：System.Web.Routing.RouteValueDictionary
			//一些约束，URL 请求必须满足这些约束才能作为此路由处理。
			//dataTokens
			//类型：System.Web.Routing.RouteValueDictionary
			//与路由关联的值，但这些值不用于确定路由是否匹配 URL 模式。
			/*Eg:
			  routes.MapPageRoute("ExpenseDetailRoute",
									"ExpenseReportDetail/{locale}/{year}/{*queryvalues}", "~/expenses.aspx",
									false,
									new RouteValueDictionary 
										{ { "locale", "US" }, { "year", DateTime.Now.Year.ToString() } },
									new RouteValueDictionary 
										{ { "locale", "[a-z]{2}" }, { "year", @"\d{4}" } },
									new RouteValueDictionary 
										{ { "account", "1234" }, { "subaccount", "5678" } });

			 */

			path = app.Server.MapPath(path);
			if (File.Exists(path))
			{
				try
				{
					XmlDocument doc = new XmlDocument();                 //获得配置文件的全路径 
					doc.Load(path);
					XmlNodeList nodes = doc.GetElementsByTagName("Route");


					nodes.Cast<XmlNode>().ToList().ForEach(route =>
					{
						string RouteName = route.Attributes["Name"].Value;
						string RouteUrl = route.Attributes["Url"].Value;
						string RouteFile = route.Attributes["File"].Value;
						RouteValueDictionary Defaults = new RouteValueDictionary();
						RouteValueDictionary Constraints = new RouteValueDictionary();
						route.SelectNodes("RouteValuesDefault/RouteValue").Cast<XmlNode>().ToList()
							.ForEach(dict => Defaults.Add(dict.Attributes["Key"].Value, dict.Attributes["Value"].Value));
						route.SelectNodes("RouteValuesConstraints/RouteValue").Cast<XmlNode>().ToList()
							.ForEach(dict => Constraints.Add(dict.Attributes["Key"].Value, dict.Attributes["Value"].Value));

						routes.MapPageRoute(RouteName, RouteUrl, RouteFile, false, Defaults, Constraints);

					});
				}
				catch (Exception ex)
				{
					LogHelper.WriteLog(ex.Message, "Url路由初始化");
				}
			}

		}

		/// <summary>
		/// 获取ip地址
		/// </summary>
		/// <returns></returns>
		public static string GetRealIp()
		{
			string user_IP = string.Empty;
			if (HttpContext.Current.IsNotNull())
			{
				if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
					user_IP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
				else
					user_IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
				return user_IP;
			}
			else
			{
				string stringIP = "";
				ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
				ManagementObjectCollection MOC = MC.GetInstances();
				foreach (ManagementObject MO in MOC)
				{
					if ((bool)MO["IPEnabled"] == true)
					{
						string[] IPAddresses = (string[])MO["IPAddress"];
						if (IPAddresses.Length > 0)
						{
							stringIP = IPAddresses[0].ToString();
						}
					}
				}
				return stringIP;
			}

		}

		public static string HttpPost(string URI, string Parameters)
		{
			System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
			//req.Proxy = new System.Net.WebProxy(ProxyString, true);

			req.ContentType = "application/x-www-form-urlencoded";
			req.Method = "POST";

			byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
			req.ContentLength = bytes.Length;

			System.IO.Stream os = req.GetRequestStream();
			os.Write(bytes, 0, bytes.Length);
			os.Close();

			System.Net.WebResponse resp = req.GetResponse();
			if (resp == null) return null;

			System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
			return sr.ReadToEnd().Trim();
		}




		public static string GetHttp(string tUrl, Encoding code)
		{
			string strResult;
			try
			{
				if (tUrl.IndexOf("http://") < 0)
					tUrl = "http://" + tUrl;
				HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl);
				hwr.Timeout = 19600;
				HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
				Stream myStream = hwrs.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, code);
				StringBuilder sb = new StringBuilder();
				while (-1 != sr.Peek())
				{
					sb.Append(sr.ReadLine() + "\r\n");
				}
				strResult = sb.ToString();
				hwrs.Close();
			}
			catch (Exception ee)
			{
				strResult = ee.Message;
			}
			return strResult;
		}

		/// <summary>
		/// 取CPU编号
		/// </summary>
		/// <returns></returns>
		public static string GetCpuID()
		{
			try
			{
				ManagementClass mc = new ManagementClass("Win32_Processor");
				ManagementObjectCollection moc = mc.GetInstances();
				string strCpuID = null;
				foreach (ManagementObject mo in moc)
				{
					strCpuID = mo.Properties["ProcessorId"].Value.ToString();
					break;
				}
				return strCpuID;
			}
			catch
			{
				return "";
			}
		}
		/// <summary>
		/// 取第一块硬盘编号
		/// </summary>
		/// <returns></returns>
		public static string GetHardDiskID()
		{
			try
			{
				ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
				string strHardDiskID = null;
				foreach (ManagementObject mo in searcher.Get())
				{
					strHardDiskID = mo["SerialNumber"].ToString().Trim();
					break;
				}
				return strHardDiskID;
			}
			catch
			{
				return "";
			}
		}
		/// <summary>
		/// 获取网卡MAC地址
		/// </summary>
		/// <returns></returns>
		public static string GetNetCardMAC()
		{
			try
			{
				string stringMAC = "";
				ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
				ManagementObjectCollection MOC = MC.GetInstances();
				foreach (ManagementObject MO in MOC)
				{
					if ((bool)MO["IPEnabled"] == true)
					{
						stringMAC += MO["MACAddress"].ToString();
					}
				}
				return stringMAC;
			}
			catch
			{
				return "";
			}
		}



		/// <summary>
		/// 串口函数(方法需调用注册表,串口编程所用类)
		/// </summary>
		/// 使用命名空间：
		/// using System.Security;
		/// using System.Security.Permissions;
		/// <returns>返回此计算机串口数组</returns>
		public static string[] GetPortNames()//
		{
			RegistryKey localMachine = null;
			RegistryKey key2 = null;
			string[] textArray = null;//这里有个判断，判断该注册表项是否存在    
			new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM").Assert();
			try
			{
				localMachine = Registry.LocalMachine;
				key2 = localMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false);
				if (key2 != null)
				{
					string[] valueNames = key2.GetValueNames();
					textArray = new string[valueNames.Length];
					for (int i = 0; i < valueNames.Length; i++)
					{
						textArray[i] = (string)key2.GetValue(valueNames[i]);
					}
				}
			}
			finally
			{
				if (localMachine != null)
				{
					localMachine.Close();
				} if (key2 != null)
				{
					key2.Close();
				}
				CodeAccessPermission.RevertAssert();
			} if (textArray == null)
			{
				textArray = new string[0];
			}
			return textArray;
		}
	}
}
